package com.itheima.reggie.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import com.itheima.reggie.vo.OrdersVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    //--1--  去支付，生成订单  请求url地址：/order/submit
    @PostMapping("/submit")
    public R saveOrder(@RequestBody Orders orders){

        //-M1:  关联数据唯一id查  user表，地址表
        Long userId = BaseContext.getCurrentId();

        User user = userService.getOne(
                new LambdaQueryWrapper<User>().eq(User::getId, userId));

        AddressBook addressBook = addressBookService.getOne(
                new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getId, orders.getAddressBookId()));

        List<ShoppingCart> shoppingCartList = shoppingCartService.list(
                new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, userId));

        long orderId = IdWorker.getId();  //订单号
        //BigDecimal amount = new BigDecimal(0);
        AtomicInteger amount = new AtomicInteger(0);//总价


        //-M2:-----------添加订单明细-------------------------------
        List<OrderDetail> orderDetailList=shoppingCartList.stream().map(item->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail);
            orderDetail.setOrderId(orderId);//订单号  ,其他数据均填充

            //amount.add(orderDetail.getAmount());  此处add不可以，加不了
            // amount 金额单独设置 数量  *  单价   此处只是记录
            int value = item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue();
            amount.addAndGet(value);
            log.info("[>>>--<订单模块>当前订单明细-数量*单价]: {}*{}={}",item.getNumber(),item.getAmount(),value);
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetailList);
        log.info("[>>>--<订单模块>当前订单{}总金额]: ￥{}",orderId,new BigDecimal(amount.get()));


        //-M3:  --------添加订单，补充各种数据-------------------------
        String orderAddress=addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName();
        orderAddress+=addressBook.getCityName() == null ? "" : addressBook.getCityName();
        orderAddress+=addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName();
        orderAddress+=addressBook.getDetail() == null ? "" : addressBook.getDetail();

        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));    //订单号
        orders.setStatus(2);         //1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);    //用户id
        //orders.setAddressBookId();
        orders.setOrderTime(LocalDateTime.now());   //订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());   //订单结账时间
        //orders.setPayMethod();
        orders.setAmount(new BigDecimal(amount.get()));   //总金额

        //orders.setRemark();
        orders.setUserName(user.getName());       //用户名
        orders.setPhone(addressBook.getPhone());  //收货人联系电话
        orders.setAddress(orderAddress);         //省+市+区域+详细地址
        orders.setConsignee(addressBook.getConsignee()); //收货人

        //---:-------添加一条订单
        ordersService.save(orders);

        //-M4:删除购物车-------------------------
        shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId,userId));
        return R.success("清空购物车成功");
    }

    //--2--  【电脑端】分页查询订单  5个参数
    //请求url地址：/order/page?page=1&pageSize=10
    //附加条件 &number=1571772354099351554 &beginTime=2022-09-05 00:00:00 &endTime=2022-10-26 23:59:59
    @GetMapping("/page")
    public R<Page> orderUserPage(@RequestParam Map map){
        log.info("[>>>--<订单模块-服务端>用户分页展示]: map={}",map);

        //--T1.取出Map
        long page = Long.parseLong(map.get("page").toString());
        long pageSize = Long.parseLong(map.get("pageSize").toString());
        Object number = map.get("number");         //订单号
        Object beginTime = map.get("beginTime");
        Object endTime = map.get("endTime");

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        LocalDateTime beginTime = LocalDateTime.parse(map.get("beginTime").toString(),df);
//        LocalDateTime endTime = LocalDateTime.parse(map.get("endTime").toString(),df);
//        log.info("page={},pageSize={},number={},beginTime={},page={}",page,pageSize,number,beginTime,endTime);

        //--T2.分页-条件查询   t(User::getAge, 30).gt(User::getAge, 10)大于10小于30
        Page<Orders> ordersPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> qwr=new LambdaQueryWrapper<>();
        if(Objects.nonNull(number)){
            qwr.like(Orders::getNumber,number.toString());
        }
        if(Objects.nonNull(beginTime)){
            qwr.gt(Orders::getOrderTime,LocalDateTime.parse(beginTime.toString(),df));
        }
        if(Objects.nonNull(endTime)){
            qwr.lt(Orders::getOrderTime,LocalDateTime.parse(endTime.toString(),df));
        }
        qwr.orderByDesc(Orders::getOrderTime);
        ordersService.page(ordersPage,qwr);

        return R.success(ordersPage);
    }

    //--2--  【电脑端】派送订单
    //PUT====Request URL: http://localhost:8080/order
    //  id: "1635996571164233729"  status: 3
    @PutMapping
    public R setsetO(@RequestBody Orders orders){
        ordersService.updateById(orders);
        return R.success("派送成功！");
    }

    //--3--  【手机端】分页查询订单
    @GetMapping("/userPage")
    public R<Page<OrdersVO>> orderPage(Long page,Long pageSize){
        log.info("[>>>--<订单模块-客户端>分页展示]: page={},pageSize={}",page,pageSize);

        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //--T1--当前订单分页条件___新订单先展示
        ordersService.page(ordersPage,
                new LambdaQueryWrapper<Orders>()
                        .eq(Orders::getUserId, BaseContext.getCurrentId()).orderByDesc(Orders::getCheckoutTime));

        //--T2--封装 List<OrdersVO>
        List<Orders> ordersList = ordersPage.getRecords();
        List<OrdersVO> ordersVOList=ordersList.stream().map(item->{
            OrdersVO ordersVO=new OrdersVO();
            BeanUtils.copyProperties(item,ordersVO);
            //遍历订单id__查订单明细__封装
            List<OrderDetail> orderDetails = orderDetailService.list(
                    new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, item.getId()));
            ordersVO.setOrderDetails(orderDetails);
            return ordersVO;
        }).collect(Collectors.toList());

        //--3--分页
        Page<OrdersVO> ordersVOPage= new Page<>();
        BeanUtils.copyProperties(ordersPage,ordersVOPage,"records");
        ordersVOPage.setRecords(ordersVOList);
        return R.success(ordersVOPage);
    }

    //--扩展二--  导出表格  请求url地址："/order/export?beginTime=000000&endTime=000000"
    //order/page?page=1&pageSize=10&beginTime=2023-03-03%2000%3A00%3A00&endTime=2023-03-11%2023%3A59%3A59
    @GetMapping("/export")
    public void download(String beginTime,String endTime,HttpServletResponse response) throws IOException {
        log.info("[>>>--<订单模块-服务端>导出表格]: beginTime={},endTime={}",beginTime,endTime);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        //String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        String fileName= UUID.randomUUID().toString();
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        LambdaQueryWrapper<Orders> qwr=new LambdaQueryWrapper<>();
        qwr.between(StringUtils.isNotEmpty(beginTime)&&StringUtils.isNotEmpty(endTime),
                Orders::getOrderTime,beginTime,endTime);
        List<Orders> ordersList = ordersService.list(qwr);
        EasyExcel.write(response.getOutputStream(), Orders.class).sheet("模板").doWrite(ordersList);
    }
}
